/* **********************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This source code is subject to terms and conditions of the Shared Source License
* for DSL Editor PowerToy. A copy of the license can be found in the License.htm file
* at the root of this distribution. If you can not locate the Shared Source License
* for DSL Editor PowerToy, please obtain a copy from: http://www.codeplex.com/dsltreegrideditor/Project/License.aspx.
* By using this source code in any fashion, you are agreeing to be bound by
* the terms of the Shared Source License for DSL Editor PowerToy.
*
* You must not remove this notice, or any other, from this software.
*
* **********************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using EnvDTE;
using EnvDTE80;

using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;

namespace DslEditorPowerToy.Recipes.Actions
{
    /// <summary>
    /// Removes a line(s) from a text file, containing specified text
    /// </summary>
    public class RemoveLineFromTextFileAction : ActionBase
    {
        private EnvDTE.Project _project = null;
        private string _targetFilePath = string.Empty;
        private string _searchExpression = string.Empty;
        private AppendOccurance _occurance = AppendOccurance.Any;

        #region Constructors
        public RemoveLineFromTextFileAction()
            : base()
        {
        }
        #endregion

        #region Public Properties
        [Input(Required = true)]
        [CLSCompliant(false)]
        public EnvDTE.Project Project
        {
            get
            {
                return this._project;
            }
            set
            {
                this._project = value;
            }
        }
        [Input(Required = true)]
        public string TargetFilePath
        {
            get
            {
                return this._targetFilePath;
            }
            set
            {
                this._targetFilePath = value;
            }
        }
        [Input(Required = true)]
        public string SearchExpression
        {
            get
            {
                return this._searchExpression;
            }
            set
            {
                this._searchExpression = value;
            }
        }
        [Input(Required = false)]
        public AppendOccurance Occurance
        {
            get
            {
                return this._occurance;
            }
            set
            {
                this._occurance = value;
            }
        }
        #endregion

        #region IAction Members

        public override void Execute()
        {
            base.Execute();
            ValidateParameters();

            //Get file from project
            string pathToFile = Path.Combine(DteHelper.BuildPath(this._project), (string)this.Evaluate(this._targetFilePath));
            ProjectItem projectItem = DteHelper.FindItemByPath(DTE.Solution, pathToFile);
            if (null == projectItem)
                return;

            try
            {
                //Open document in silent mode
                projectItem.Open(Constants.vsViewKindTextView);

                //Get to start of text document
                TextDocument document = projectItem.Document.Object("TextDocument") as TextDocument;
                EditPoint editPoint = document.CreateEditPoint(null);

                //Find first Match
                EditPoint endPoint = null;
                TextRanges tags = null;
                string searchExpression = Regex.Escape((string)this.Evaluate(Regex.Unescape(this._searchExpression)));
                bool found = editPoint.FindPattern(searchExpression, (int)(FindOptions.RegularExpression | FindOptions.FromStart),
                    ref endPoint, ref tags);
                if (false == found)
                    return;

                while (true == found)
                {
                    if (AppendOccurance.First == this._occurance)
                    {
                        //Only remove first match
                        RemoveLine(editPoint, editPoint.Line);
                        break;
                    }
                    else if (AppendOccurance.Any == this._occurance)
                    {
                        //Remove all matched
                        RemoveLine(editPoint, editPoint.Line);
                    }

                    //Find next Match
                    editPoint.MoveToAbsoluteOffset(endPoint.AbsoluteCharOffset);
                    endPoint = null;
                    tags = null;
                    found = editPoint.FindPattern(searchExpression, (int)(FindOptions.RegularExpression),
                    ref endPoint, ref tags);
                }
                if (AppendOccurance.Last == this._occurance)
                {
                    //Remove last matched
                    RemoveLine(editPoint, editPoint.Line);
                }


                //Ensure it is closed
                projectItem.Document.Close(vsSaveChanges.vsSaveChangesYes);
            }
            finally
            {
                //Ensure its closed
                if (null != projectItem.Document)
                    projectItem.Document.Close(vsSaveChanges.vsSaveChangesNo);
            }
        }
        public override void Undo()
        {
            //Do undo action, or explain why you can't or should not
        }

        #endregion

        #region Protected Methods
        /// <summary>
        /// Validates parameters before execution
        /// </summary>
        protected override void ValidateParameters()
        {
            if (null == this._project)
                throw new ArgumentNullException("Project");
            if (null == this._targetFilePath)
                throw new ArgumentNullException("TargetFilePath");
            if (0 == this._targetFilePath.Length)
                throw new ArgumentOutOfRangeException("TargetFilePath");
            if (null == this._searchExpression)
                throw new ArgumentNullException("SearchText");
            if (0 == this._searchExpression.Length)
                throw new ArgumentOutOfRangeException("SearchText");
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Removes given line of text
        /// </summary>
        private void RemoveLine(EditPoint editPoint, int line)
        {
            //Move to position
            editPoint.MoveToLineAndOffset(line, 1);

            //Delete line (plus newline char)
            ((EditPoint2)editPoint).Delete(editPoint.LineLength + 1);
        }
        #endregion
    }
}